package com.zhouyibike.uu.ui.activity.mybike;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.ProductPayTypeResult;
import com.zhouyibike.uu.entity.YiBuyBicycleResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.RGSMActivity;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.DataSingle;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class RengoujiesuanActivity extends BaseActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private CheckBox cb_wx, cb_zfb;
    private String paytype = "1";//支付方式
    private Button btn_zhifu;
    private IWXAPI api;
    private ProductPayTypeResult chuandiProductPayTypeResult;
    private int buycount = 0;
    private double moneycount = 0;
    private int yiquancount = 0;
    private int buytype = 0;//购买方式
    private LinearLayout zfbly, wxly, yqly;
    private ImageView buydancheiv;
    private TextView buydanchetitle, jiesuanprice, jiesuannum, yiquannum,zhouyidanchehuodongxieyi;
    private Dialog jubaodialog;
    private Animation operatingAnim;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rengoujiesuan);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        chuandiProductPayTypeResult = (ProductPayTypeResult) getIntent().getSerializableExtra("bikeinfo");
        buycount = getIntent().getIntExtra("buycount", 0);
        moneycount = getIntent().getDoubleExtra("buyonemoney", 0);
        yiquancount = getIntent().getIntExtra("buyoneyiquan", 0);
        buytype = getIntent().getIntExtra("buytype", 0);
        initView();
        setjubaoDialog2();
        settixiannewDialog();
        initListener();
    }
    private void initListener() {
        cb_wx.setOnCheckedChangeListener(this);
        cb_zfb.setOnCheckedChangeListener(this);
        zhouyidanchehuodongxieyi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getWZMsg();
            }
        });
    }
    private void initView() {
        zhouyidanchehuodongxieyi= (TextView) findViewById(R.id.zhouyidanchehuodongxieyi);
        buydancheiv = (ImageView) findViewById(R.id.buydancheiv);
        buydanchetitle = (TextView) findViewById(R.id.buydanchetitle);
        jiesuanprice = (TextView) findViewById(R.id.jiesuanprice);
        jiesuannum = (TextView) findViewById(R.id.jiesuannum);
        yiquannum = (TextView) findViewById(R.id.yiquannum);
        Picasso.with(this).load(chuandiProductPayTypeResult.getData().getProductImg()).error(R.drawable.zhanweitu).placeholder(R.drawable.zhanweitu).networkPolicy(NetworkPolicy.NO_CACHE,NetworkPolicy.NO_STORE).into(buydancheiv);
        buydanchetitle.setText(chuandiProductPayTypeResult.getData().getContent());
        jiesuanprice.setText(" ￥" + (moneycount * buycount));
        jiesuannum.setText(" " + buycount + "辆");
        yiquannum.setText(" " + (yiquancount * buycount) + "张");
        wxly = (LinearLayout) findViewById(R.id.wxly);
        zfbly = (LinearLayout) findViewById(R.id.zfbly);
        yqly = (LinearLayout) findViewById(R.id.yiquanly);
        if (moneycount != 0) {
            yqly.setVisibility(View.GONE);
        } else {
            View view=findViewById(R.id.xian1);
            view.setVisibility(View.GONE);
            view=findViewById(R.id.xian2);
            view.setVisibility(View.GONE);
            wxly.setVisibility(View.GONE);
            zfbly.setVisibility(View.GONE);
        }
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("订单详情");
        mBtnBack.setOnClickListener(this);
        cb_wx = (CheckBox) findViewById(R.id.cb_chongzhi_wx);
        cb_zfb = (CheckBox) findViewById(R.id.cb_chongzhi_zfb);
        btn_zhifu = (Button) findViewById(R.id.btn_chongzhiactivity_zhifu);
        btn_zhifu.setOnClickListener(this);
    }

    //"token" -> "-JunxHxb-Gz4hXx3fMunbAYdNSsd3n15LQdzuB2_BXs1vmcd3h0HkPyMjH2MgXm0_B24HTcFFMfqZx3ejLgdLsDBZx3efbgdFDdnx0EFLGe2Hd4deXl5eXl5eXlKeXl5eUp5eXl5Snl5eXlKeXl5eXl5eXl5eXl5HU8"
    private void zhifu() {
        if (buytype == 3 && yiquancount != 0 && moneycount == 0)//翼券支付
        {
            Map<String, String> params = new HashMap<>();
            params.put("token", preferences.getString("token", ""));
            params.put("typeId", buytype + "");
            params.put("count", buycount + "");
            showProgressDialog();
            addSubscription(apiStores.YiBuyBicycle(params),
                    new ApiCallback<YiBuyBicycleResult>() {
                        @Override
                        public void onSuccess(YiBuyBicycleResult model) {
                            if (model.getStatus() == Config.SUCCESSCODE) {
                                paysuccess();
                            } else {
                                toastShow(model.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            toastShow(msg);

                        }

                        @Override
                        public void onFinish() {
                            dismissProgressDialog();
                        }
                    });
        } else {//现金支付
            Map<String, String> params = new HashMap<>();
            params.put("token", preferences.getString("token", ""));
            params.put("typeId", buytype + "");
            params.put("count", buycount + "");
            showProgressDialog();
            addSubscription(apiStores.YiBuyBicycle(params),
                    new ApiCallback<YiBuyBicycleResult>() {

                        @Override
                        public void onSuccess(YiBuyBicycleResult model) {
                            if (model.getStatus() == Config.SUCCESSCODE) {
//                            paysuccess();
                                if (paytype.equals("2")) {//支付宝
                                    zfbpay(model.getData().getAlipay());
                                } else {
//                                model.getData().getWeChatPay();
//                                model.getData().getWeChat();
                                    wxpay(model.getData().getWeChatPay());
                                }
                            } else {
                                toastShow(model.getMessage());
                            }
                        }

                        @Override
                        public void onFailure(String msg) {
                            toastShow(msg);

                        }

                        @Override
                        public void onFinish() {
                            dismissProgressDialog();
//                        paysuccess();
//                        String zfb="\"app_id=2017041206669129&biz_content=%7B%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22total_amount%22%3A%220.02%22%2C%22subject%22%3A%22%E8%B4%AD%E4%B9%B0%E7%BF%BC%E5%88%B8%22%2C%22body%22%3A%22%E8%B4%AD%E4%B9%B0%E7%BF%BC%E5%88%B8%22%2C%22out_trade_no%22%3A%22ceb6a7d57b5a11e7ae1293349ff1e13c%22%7D&charset=utf-8&method=alipay.trade.app.pay&notify_url=http%3A%2F%2F47.93.46.52%3A8765%2FPayment%2FAlipayCallBack&sign=PgzwsQl81CDxu%2Bo4oJUaoe6qGCGfC7esIDm2OTteeI5i5oGiI%2FRuu%2F5z2EbGsZvaTYzz74ZAF6IHEHqu4hoDEnDwiXp09Oaalh4PUOUOb77ga4vJ4%2Faw8qwc5TKmfm7J%2B%2BKqjjDEyerRNdk7TtLThr9NsH2d3LgrqcMpWiPrY9c%3D&sign_type=RSA&timestamp=2017-08-07+18%3A26%3A02&version=1.0\"";
//                        zfbpay(zfb);
                        }
                    });
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()) {
            case R.id.cb_chongzhi_wx:
                if (isChecked) {
                    cb_zfb.setChecked(false);
                    paytype = "1";
                } else {
                    cb_zfb.setChecked(true);
                    paytype = "2";
                }
                break;
            case R.id.cb_chongzhi_zfb:
                if (isChecked) {
                    cb_wx.setChecked(false);
                    paytype = "2";
                } else {
                    cb_wx.setChecked(true);
                    paytype = "1";
                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.btn_chongzhiactivity_zhifu:
                jubaodialogzz.show();
//                zhifu();
                break;
            default:
                break;
        }
    }

    private void wxpay(YiBuyBicycleResult.DataBean.WeChatPayBean model) {
        api.registerApp(model.getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if (!isPaySupported) {
            Toast.makeText(RengoujiesuanActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(RengoujiesuanActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try {
            PayReq request = new PayReq();

            request.appId = model.getAppId();

            request.partnerId = model.getPartnerId();

            request.prepayId = model.getPrepayId();

            request.packageValue = model.getPackageX();

            request.nonceStr = model.getNoncestr();

            request.timeStamp = model.getTimestamp();

            request.sign = model.getSign();

            api.sendReq(request);

        } catch (Exception e) {
            Toast.makeText(RengoujiesuanActivity.this, "异常：" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if (progress == 0) {//支付成功
            paysuccess();
        } else {
            Toast.makeText(RengoujiesuanActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }

    private void zfbpay(final String orderinfo) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(RengoujiesuanActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(RengoujiesuanActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };

    private void paysuccess() {
        setResult(1);
        EventBus.getDefault().post("buybikeok");
        jubaodialog.show();
//        intent.putExtra("payamont",payamont);
//        startActivityForResult(intent,400);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
    private void getWZMsg() {
        startActivity(new Intent(RengoujiesuanActivity.this, RGSMActivity.class));
    }
    private void setjubaoDialog2() {
        setrotatanim();
        TextView wodanche;
        ImageView iv,closeiv;
        LayoutInflater inflater = LayoutInflater.from(RengoujiesuanActivity.this);
        final View headview = inflater.inflate(R.layout.xuanzhuan_ok_dialog, null, false);
        jubaodialog = new Dialog(this, R.style.Dialog_Fullscreen);
        jubaodialog.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        jubaodialog.setCanceledOnTouchOutside(false);
        iv=headview.findViewById(R.id.xuanzhuaniv);
        closeiv=headview.findViewById(R.id.closeiv);
        wodanche=headview.findViewById(R.id.wodanche);
        Window dialogWindow = jubaodialog.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = (int) (DataSingle.getInstance().PhoneW); // 宽度
        lp.height = (int) (DataSingle.getInstance().PhoneW);
        dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        jubaodialog.setOnKeyListener(keylistener);
        iv.startAnimation(operatingAnim);
        closeiv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
            }
        });
        wodanche.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialog.dismiss();
                setResult(2);
                finish();
            }
        });
    }
    private void setrotatanim() {
        operatingAnim = AnimationUtils.loadAnimation(this, R.anim.myrotating);
        operatingAnim.setRepeatCount(-1);
        operatingAnim.setFillAfter(false);
        operatingAnim.setDuration(5000);
        LinearInterpolator lin = new LinearInterpolator();
        operatingAnim.setInterpolator(lin);
    }
    //对话框1
    Dialog jubaodialogzz;
    private void settixiannewDialog() {
        TextView tixiandialogquxiao, tixiandialogqueding, note1,note2;
        ImageView xuzhi;
        LayoutInflater inflater = LayoutInflater.from(RengoujiesuanActivity.this);
        final View headview = inflater.inflate(R.layout.tixiantishi_dialog, null, false);
        tixiandialogquxiao = headview.findViewById(R.id.tixiandialogquxiao);
        tixiandialogqueding = headview.findViewById(R.id.tixiandialogqueding);
        note2 = headview.findViewById(R.id.note2);
        xuzhi= headview.findViewById(R.id.xuzhi);
        note1= headview.findViewById(R.id.notes);
//        note1.setVisibility(View.GONE);
        xuzhi.setVisibility(View.GONE);
        note2.setText("您确定购买单车吗?");
        jubaodialogzz = new Dialog(this, R.style.Dialog_Fullscreen);
        jubaodialogzz.setContentView(headview, new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        jubaodialogzz.setCanceledOnTouchOutside(false);
        Window dialogWindow = jubaodialogzz.getWindow();
        dialogWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
//        adjustPan|stateHidden
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        dialogWindow.setGravity(Gravity.CENTER);
//                lp.x = 100; // 新位置X坐标
//          lp.y = 100; // 新位置Y坐标
        lp.width = (int) (DataSingle.getInstance().PhoneW * 0.75); // 宽度
//        lp.height = (int) (DataSingle.getInstance().PhoneW * 0.75);
//         lp.alpha = 0.7f; // 透明度
        // 当Window的Attributes改变时系统会调用此函数,可以直接调用以应用上面对窗口参数的更改,也可以用setAttributes
        // dialog.onWindowAttributesChanged(lp);
        dialogWindow.setWindowAnimations(R.style.mypopwindow_anim_style3);  //添加动画
        dialogWindow.setAttributes(lp);
        tixiandialogquxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialogzz.dismiss();
            }
        });
        tixiandialogqueding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jubaodialogzz.dismiss();
                zhifu();
            }
        });
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        jubaodialogzz.setOnKeyListener(keylistener);
    }
}
